<template>
  <el-dialog
    v-model="dialogTableVisible"
    :title="title"
    :close-on-press-escape="false"
    :close-on-click-modal="false"
    :show-close="false"
    :draggable="true"
    @before-close="() => false"
    append-to-body
    style="width: 50%"
  >
    <FormBase :mode="mode" @on-submit="onSubmit" @on-cancel="handleClose">
      <div class="editor-container">
        <el-form
          ref="newsForm"
          :model="dataModel"
          label-width="auto"
          :rules="rules"
          style="width: 100%"
        >
          <el-form-item :label="t('新闻标题')" prop="title">
            <el-input v-model="dataModel.title" :disabled="mode === 'view'" />
          </el-form-item>
          <el-form-item :label="t('新闻副标题')" prop="subTitle">
            <el-input v-model="dataModel.subTitle" :disabled="mode === 'view'" />
          </el-form-item>
          <el-form-item :label="t('新闻描述')" prop="description">
            <el-input v-model="dataModel.description" :disabled="mode === 'view'" />
          </el-form-item>
          <el-form-item :label="t('新闻内容')" prop="content">
            <VRichEditor v-model="dataModel.content" :disabled="mode === 'view'"></VRichEditor>
          </el-form-item>
          <el-form-item :label="t('新闻封面')" prop="originImg">
            <VImage
              ref="uploadImage"
              :src="dataModel.originImg"
              :autoUpload="false"
              fit="contain"
              :disabled="mode === 'view'"
            >
            </VImage>
          </el-form-item>
        </el-form>
      </div>
    </FormBase>
  </el-dialog>
</template>
<script setup lang="ts">
import { computed, onMounted, onUnmounted, reactive, ref, watch } from 'vue'
import { t } from '@/common/locale'
import { FormRules } from 'element-plus'
import { add, getNewsDetail, update } from '@/api/news'
import elHelper from '@/common/elHelper'
import VImage from '../other/VImage.vue'
import VRichEditor from '../other/VRichEditor.vue'
import comFunc from '@/common/comFunc'
import FormBase from '../layout/FormBase.vue'

const props = defineProps({
  data: {
    type: Object,
    default: {}
  },
  mode: {
    type: String,
    validator: (val: string) => {
      return ['add', 'modify'].includes(val)
    },
    default: 'add'
  },
  show: {
    type: Boolean,
    default: false
  }
})
const emit = defineEmits(['onSubmited', 'update:show'])

const title = computed(() => {
  switch (props.mode) {
    case 'add':
      return t('新增')
    case 'modify':
      return t('修改')
    case 'view':
      return t('查看')
  }
})

const dataModel: NewsDataModel = reactive({
  desc: '',
  title: '',
  originImg: '',
  objectId: '',
  subTitle: '',
  content: ''
})
Object.assign(dataModel, props.data)
const uploadImage = ref()
const mode = ref(props.mode)
const dialogTableVisible = ref(false)
const newsForm = ref()
const rules = reactive<FormRules<NewsDataModel>>({
  title: [{ required: true, message: t('请输入标题'), trigger: 'blur' }]
})
watch(
  () => props.show,
  async (val) => {
    dialogTableVisible.value = val
    if (val) {
      Object.assign(dataModel, props.data)
      mode.value = props.mode
      await getInfo()
    } else {
      dataModel.description = ''
      dataModel.content = ''
      dataModel.subTitle = ''
      dataModel.objectId = ''
      dataModel.originImg = ''
      dataModel.thumbImg = ''
      dataModel.title = ''
      uploadImage.value?.clear()
    }
  }
)
const onSubmit = async () => {
  let valid = await newsForm.value.validate((valid) => {
    if (!valid) {
      elHelper.showErrorMsg('校验失败：请修正后再提交')
    }
    return valid
  })
  if (valid) {
    const reUpload = await uploadImage.value?.upload()
    if (!reUpload.isSuccess) {
      elHelper.showErrorMsg(reUpload.msg)
      return
    }
    dataModel.originImg = reUpload.path
    if (mode.value === 'add') {
      const re = await add(dataModel)
      if (re.isSuccess) {
        emit('onSubmited', re.data!)
        elHelper.showSuccessMsg('操作成功')
        handleClose()
      } else {
        elHelper.showErrorMsg(re.msg)
      }
    } else {
      const re = await update(dataModel)
      if (re.isSuccess) {
        emit('onSubmited', re.data!)
        elHelper.showSuccessMsg('操作成功')
        handleClose()
      } else {
        elHelper.showErrorMsg(re.msg)
      }
    }
  }
}
const handleClose = () => {
  dialogTableVisible.value = false
  emit('update:show', false)
}
const getInfo = async () => {
  if (!dataModel.objectId) return
  const re = await getNewsDetail(comFunc.nvl(dataModel.objectId))
  if (re.isSuccess) {
    Object.assign(dataModel, re.data)
  }
}
onMounted(async () => {})
onUnmounted(() => {
  handleClose()
})
</script>
<style lang="scss" scoped>
.editor-container {
  width: 98%;
  display: flex;
  justify-content: center;
  justify-items: center;
}
</style>
